{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# ONNX ModelProto 属性\n",
    "在 ONNX 中，ModelProto 通常存储计算图之外的额外信息，例如 `ir_version` 或 `producer_name`。通过向 `script`（或 `to_model_proto`）调用传递额外的命名参数，可以设置生成的 `ModelProto` 的这些属性，如下例所示。只有以这种方式指定的 `protobuf` 消息 `ModelProto` 中定义的有效字段才应被指定。\n",
    "\n",
    "首先，我们在 onnxscript 中定义一个平方损失函数的实现。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import onnx\n",
    "\n",
    "from onnxscript import FLOAT, script\n",
    "from onnxscript import opset15 as op\n",
    "\n",
    "\n",
    "@script(ir_version=7, producer_name=\"OnnxScript\", producer_version=\"0.1\")\n",
    "def square_loss(X: FLOAT[\"N\"], Y: FLOAT[\"N\"]) -> FLOAT[1]:  # noqa: F821\n",
    "    diff = X - Y\n",
    "    return op.ReduceSum(diff * diff, keepdims=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "打印："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<\n",
      "   ir_version: 7,\n",
      "   opset_import: [\"\" : 15],\n",
      "   producer_name: \"OnnxScript\",\n",
      "   producer_version: \"0.1\"\n",
      ">\n",
      "square_loss (float[N] X, float[N] Y) => (float[1] return_val) {\n",
      "   diff = Sub (X, Y)\n",
      "   tmp = Mul (diff, diff)\n",
      "   return_val = ReduceSum <keepdims: int = 1> (tmp)\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "model = square_loss.to_model_proto()\n",
    "print(onnx.printer.to_text(model))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "xin",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
